

var core = {
    
    dialog: null,
    dialogCanClose: false,
    
    init: function() {
        this.setupSidebar();
        this.setupGrids();
        this.setupDialog();
        this.setupFlyout();
        this.setupButtonsAndMenus();
        this.setupAutoLogout();
    },
    
    setupGrids: function() {
        $("input.check_all").live("change", function(e) {
            if( $(this).is(":checked") ) {
                $(this).parents("table.fullwidth").find("tbody input[type=checkbox]").attr("checked","checked");
            } else {
                $(this).parents("table.fullwidth").find("tbody input[type=checkbox]").removeAttr("checked");
            }
        });
        
        $("table.fullwidth tbody tr").live('click', function(e) {
            if( !$(this).hasClass('selected') ) {
                $(this).parents("table").find("tr").removeClass("selected");
                $(this).addClass("selected").focus();
            }
        });
        
        $("table.fullwidth tbody tr").live('keyup', function(e) {
            var selected = $(this).parents("table").find("tr.selected");
            
            if( e.keyCode == 38 && selected.prev("tr").length > 0 ) {
                selected.removeClass("selected");
                selected.prev("tr").addClass("selected").click();
            }
            
            else if( e.keyCode == 40 && selected.next("tr").length > 0 ) {
                selected.removeClass("selected");
                selected.next("tr").addClass("selected").click();
            }
            
        }).attr("tabIndex", 1);
        
        $(".fullwidth tbody tr a.delete_link").live('click', function(e) {
            e.preventDefault();
            
            if( !confirm("Are you sure you want to delete the selected item?") ) {
                return;
            }
            
            var url = $(this).attr('href');
            var tr = $(this).parents("tr");
            
            $.get(url, function() {
                tr.remove();
            });
        });
        
        $(".columns .subheader .delete_selected").click( core.deleteSelected );
    },
    
    setupDialog: function() {
        this.dialog = $("#general_dialog").dialog({
            autoOpen: false,
            width: '700',
            height: '400',
            modal: true
        });
        
        $("#submit_frame").load(function(e) {
            e.preventDefault();

            if( core.dialogCanClose ) {
                core.dialog.dialog('close');
                core.dialogCanClose = false;
                
                window.history.go(0);
            }
        });
        
        $(".dialog_opener").live('click', function(e) {
            e.preventDefault();
          
            var $opener = $(this);
            var url = $opener.attr("href") || $opener.data('url');
            var title = $opener.attr("title");
            var callback = $opener.data("callback");
            var load = $opener.data('load-callback');
            
            $.get(url, function(content) {
                core.showDialog({
                    title: title, 
                    content: content,
                    width: $opener.data('width'),
                    height: $opener.data('height'),
                    load: load,
                    close: callback
                });
            });
        });
    },
        
    setupFlyout: function() {
        $(".flyout_opener").live('click', function(e) {
            e.preventDefault();


            var url = $(this).attr("href") || $(this).data('url');
            var title = $(this).attr("title");
            var callback = $(this).data('callback');
            var load_callback = $(this).data("load-callback");

            if(url=="#")
            {
                return;
            }

            var query = "";
            
            $("#flyout .content").html("Loading...").show("slow");
                
            $.get(url, query, function(content) {
                core.showFlyout({
                    title: title, 
                    content: content,
                    load: load_callback,
                    close: callback
                });
            });
        });
        
        $("#flyout .closer_btn").click(function() {
            core.closeFlyout();
        });
    },
    
    setupSidebar: function() {
        
        if( "localStorage" in window ) {
            core.showSidebar(localStorage.getItem("sidebarVisible") == "true");
        }
        
        $("#sidebar-closer").click(function() {
            core.showSidebar(false);
        });
        
        $("#sidebar-shower").click(function() {
            core.showSidebar(true);
        });
        
        directory_tools.init();
    },
    
    setupAutoComplete: function() {
        $("input.caa").autocomplete({
			source: $("#country-auto-complete-source").val(),
			minLength: 2
			/*select: function( event, ui ) {
				log( ui.item ?
					"Selected: " + ui.item.value + " aka " + ui.item.id :
					"Nothing selected, input was " + this.value );
			}*/
        });
    },
        
    closeDialog: function() {
        this.dialog.dialog('close');
    },
        
    closeFlyout: function() {
        $("#flyout").hide('slow');
    },
    
    closeResultsFlyout: function() {
        $("#results_flyout").hide('slow');
        $(".dir_tools #search_field").focus();
        
        core.executeFunction( $("#results_flyout").data('onClose') );
    },
    
    showDialog: function(options) {
        var _options = {
            title: 'Dialog Title',
            content: '<div></div>',
            height: 400,
            width: 700,
            load: function() {},
            close: function() {}
        };
        
        $.extend(true, _options, options);
        
        // remove any previously bound functions
        this.dialog.unbind('dialogopen');
        
        // bind load event
        if( $.isFunction(_options['load']) ) {
            this.dialog.bind('dialogopen', _options['load']);
        }
        
        else {
            this.dialog.bind('dialogopen', function() {
                core.executeFunction( _options['load'] ); 
            });
        }
        
        $("#general_dialog").html( _options['content'] );
        
        this.dialog.dialog("option","title", _options['title']);
        this.dialog.dialog("option","height", parseInt(_options['height']));
        this.dialog.dialog("option","width", parseInt(_options['width']));
        this.dialog.dialog("open");
        
        $("#general_dialog .chosen").chosen();
        
        $("#general_dialog #cancel-form").click(function() {
            core.dialog.dialog('close');
        });

        $("#general_dialog form").submit(function(e) {

            if( this.checkValidity ) {
                if( !this.checkValidity() ) {
                    return false;
                }
            }

            core.dialogCanClose = true;
                
            var url = $(this).attr("action");
            var query = $(this).serialize();
            
            $.ajax({
                url: url,
                data: query,
                type: 'post',
                success: function(data) {
                    core._handleFormSubmit(data, _options['close']);
                },
                error: function(xhr) {
                    console.log(xhr.responseText);
                }
            });
                
            core.closeDialog();

            return false;
        }); 
    },
        
    showFlyout: function(options) {
        
        var _options = {
            title: 'Dialog Title',
            content: '<div></div>',
            load: function() {},
            close: function() {}
        };
        
        $.extend(true, _options, options);

        $("#flyout .content").html( _options['content'] );
        $("#flyout").show("slow");
        $("#flyout .chosen").chosen();
        
        //if( $.isFunction(_options['load']) ) {
           core.executeFunction( _options['load'] );
        //}
        
        $("#flyout #cancel-form").click(function() {
            core.closeFlyout();
        });

        $("#flyout form").submit(function(e) {

            if( this.checkValidity ) {
                if( !this.checkValidity() ) {
                    return false;
                }
            }
                
            var url = $(this).attr("action");
            var query = $(this).serialize();
            
            $.ajax({
                url: url,
                data: query,
                type: 'post',
                success: function(data) {
                    core._handleFormSubmit(data, _options['close']);
                },
                error: function(xhr) {
                    console.log(xhr.responseText);
                }
            });
                
            core.closeFlyout();

            return false;
        });
    },
    
    showSidebar: function(show) {
        if( show ) {
            $("#sidebar").show('fast');
            $("#bgwrap #content").removeClass("hidden");
            $("#bgwrap #content #main").css("margin-left", "290px");
            $("#sidebar-shower").hide();
        }
        
        else {
            $("#sidebar").hide('fast');
            $("#bgwrap #content").addClass("hidden")
            $("#bgwrap #content #main").css("margin-left", "20px");
            $("#sidebar-shower").show();
        }
        
        if( "localStorage" in window ) {
            localStorage.setItem("sidebarVisible", show);
        }
    },
    
    showResultsFlyout: function(options) {
        var _options = {
            title: 'Search Results',
            content: "",
            width: 400,
            height: 'auto',
            load: function() {},
            close: function() {}
        };
        
        $.extend(true, _options, options);
        
        $("#results_flyout h3").html( _options['title'] );
        $("#results_flyout #results_pane").html( _options['content'] );
        
        core.executeFunction( _options['load'] );
        
        $("#results_flyout").data({
            'onClose': _options['close']
        }).css({
            width: _options['width'], 
            height: _options['height']
        }).show('fast');
    },
        
    _handleFormSubmit: function(data, callback) {
        // if the response is in valid JSON, parse it so it can be used
        // in the callback as necessary
        try {
            data = JSON.parse(data);
        } catch(e) {}

        if( callback && $.isFunction(callback) ) {
            callback(data);
        }

        else if ( callback && typeof callback === "string" ) {
            core.executeFunctionByName(callback, window, data);
        }
    },
        
    executeFunctionByName: function(functionName, context /*, args */) {
            
        if( !context ) {
            context = window;
        }
            
        var args = Array.prototype.slice.call(arguments).splice(2);
        var namespaces = functionName.split(".");
        var func = namespaces.pop();
        for(var i = 0; i < namespaces.length; i++) {
            context = context[namespaces[i]];
        }
        
        if( !context[func] ) {
            console.log(func + " cannot be found in the " + context + " context");
            return false;
        }
        
        return context[func].apply(this, args);
    },
    
    executeFunction: function(func /*, args */) {
        
        if( func && typeof func == "string" ) {
            core.executeFunctionByName(func, window, args);
        }
        
        else if( func && $.isFunction(func) ) {
            var args = Array.prototype.slice.call(arguments).splice(1);
            func.apply(this, args);
        }
    },
    
    deleteSelected: function(e) {
        e.preventDefault();
        
        var $inputs = $("#users_column table.fullwidth tbody tr input:checked");
            
        if( $inputs.length == 0 ) {
            alert("Please Select Records To Remove From System");
            return;
        }
            
        else {
            if( !confirm("Delete Selected Records and Related Data From System?") ) {
                return;
            }
        }
            
        var ids = [];
        $inputs.each(function() {
            ids.push( $(this).val() );
        });
            
        var query = "ids=" + ids;
        var url = $(this).attr("href");
            
        $.post(url, query, function() {
                
            $inputs.each(function() {
                $(this).parents("tr").remove();
            });
        });
    },
    
    setupButtonsAndMenus: function() {
        $(".menu_button:not(.menued) .menu").blur(function() {
            $(this).hide();
        }).each(function() {
            this.tabIndex = 1;
        });
        
        $(".menu_button:not(.menued)").click(function() {
            
            if( $(this).hasClass('activatable') && !$(this).hasClass('active') ) {
                return;
            }
            
            var $menu = $(this).find(".menu");
            
            if( $menu.is(":visible") ) {
                $menu.hide();
            } else{
                
                if( $menu.hasClass('above') ) {
                    $menu.css({top: -$menu.height()});
                }
                
                $menu.show().focus();
            }
        }).addClass('menued');
    },
    
    setupAutoLogout: function() {
        var timer = null;
        
        var logout = function() {
            window.location.href = $("#logout-url").val();
        };
        
        var setTimer = function() {
            timer = setInterval(logout, 1000 * 60 * 10);
        };
        
        var reset = function() {
            clearInterval(timer);
            setTimer();
        };
        
        $("body").mousemove(reset).click(reset).keypress(reset).scroll(reset);
        setTimer();
    }
};

$(document).ready(function() {
    core.init();
});
